package com.log.com.log.service.impl;

import java.text.SimpleDateFormat;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.log.com.log.bean.LogBaseBean;
import com.log.com.log.bean.LogInfoBean;
import com.log.com.log.bean.LogWriterBean;

/**
 * 日志service
 * @author dell
 *
 */
public class JLogBaseService extends Thread{

	private JLogBaseService  jlog=null;
	
	/**
	 * 阻塞队列
	 */
	private BlockingQueue<LogInfoBean> qeque=new  LinkedBlockingQueue<LogInfoBean>();
	
	/**
	 * 写日志的Service
	 */
	private LogWriterService log=null;
	
	/**
	 * 日志基础bean
	 */
	private LogBaseBean bean=new LogBaseBean();
	
	/**
	 * 写如文件的bean
	 */
	private LogWriterBean writerBean=new LogWriterBean()  ;
	
	/**
	 * 存储内容
	 */
	StringBuilder builder=new StringBuilder(); 
	
	/**
	 * 构造函数 
	 * @param bean  基础bean
	 * @param format  生成日志文件的时间格式串
	 * @param time   日志文件的颗粒度，控制日志时间 单位分钟计算  
	 */
	public JLogBaseService(SimpleDateFormat headFormat,String format,int time) {
		this.bean.setFormat(headFormat);
		log=new LogWriterService(format);
		this.writerBean.setTimeSpace(time*60000);
		jlog=this;
		jlog.setName(format);
		jlog.start();
	}
	
	/**
	 * 构造函数
	 * @param bean 基础bean
	 * @param format  生成日志文件的时间格式串
	 */
	public JLogBaseService(SimpleDateFormat headFormat,String format) {
		this.bean.setFormat(headFormat);
		log=new LogWriterService(format);
		jlog=this;
		jlog.setName(format);
		jlog.start();
	}
	
	
	/**
	 * 
	 * @param msg  日志内容
	 */
	public void saveTrace(String msg){
		if(log==null){
			return ;
		}
		
		long nowTime=System.currentTimeMillis();
	   
		builder.delete(0, builder.length());
		
		if(jlog==null){
			try {
				
				if(!log.writerLog(nowTime, writerBean, msg)){
					System.err.println(writerBean.getErrorContent());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			qeque.add(new LogInfoBean(nowTime, msg));
		}
	}
	
	
	
	@Override
	public synchronized void start() {
		
		if(getState()==Thread.State.NEW){
			setDaemon(false);   //设置守护线程 true  用户线程 fasle 注意这两者的区别
			super.start();
		}
	}
	
	/**
	 * 从队列中取出来数据然后写如到硬盘上
	 */
	@Override
	public void run() {
		while (true){
			
			try {
				LogInfoBean  bean=qeque.poll(1, TimeUnit.SECONDS);
				if(bean!=null && log !=null){
					log.writerLog(bean.getLogTime(), writerBean,bean.getLogMessage());
				}
					
			}  catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}
}
